package com.aishua.fire.service.impl;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aishua.fire.entity.activiti.AllSignStateInfo;
import com.aishua.fire.entity.activiti.SignTaskListInfo;
import com.aishua.fire.entity.activiti.SingUserInfo;
import com.aishua.fire.entity.activiti.WorkFlowInfo;
import com.aishua.fire.entity.activiti.YuAnActivitiDetailsRespInfo;
import com.aishua.fire.entity.activiti.YuAnActivitiPositionRespInfo;
import com.aishua.fire.entity.activiti.YuAnProcessReqInfo;
import com.aishua.fire.entity.activiti.YuAnWorkFlowStartInfo;
import com.aishua.fire.entity.activiti.YuAnWorkFlowStartParm;
import com.aishua.fire.entity.activiti.YuAnactivitiWarnRespInfo;
import com.aishua.fire.entity.activiti.YuanProcessInfo;
import com.aishua.fire.entity.activiti.YuanWarnStartUpRespInfo;
import com.aishua.fire.entity.app.AppDutyContentInfo;
import com.aishua.fire.entity.emergencyPre.EmergencyEvacuationReqInfo;
import com.aishua.fire.entity.emergencyPre.EmergencyPreDetailsRespInfo;
import com.aishua.fire.entity.emergencyPre.EmergencyPreReqInfo;
import com.aishua.fire.entity.emergencyPre.EmergencyPreRespInfo;
import com.aishua.fire.entity.emergencyPre.EmergencyWarnReqInfo;
import com.aishua.fire.entity.emergencyPre.EmergencyWarnStartUpReqInfo;
import com.aishua.fire.entity.emergencyPre.OrganizationName;
import com.aishua.fire.entity.emergencyPre.PositionContentInfo;
import com.aishua.fire.entity.emergencyPre.PositionReqInfo;
import com.aishua.fire.entity.emergencyPre.PositionRespInfo;
import com.aishua.fire.entity.emergencyPre.TroubleReqInfo;
import com.aishua.fire.entity.emergencyPre.TroubleRespInfo;
import com.aishua.fire.mapper.EmergencyPreMapper;
import com.aishua.fire.mapper.YuAnActivitiMapper;
import com.aishua.fire.service.EmergencyPreManagerService;
import com.github.pagehelper.PageHelper;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class EmergencyPreManagerServiceImpl implements EmergencyPreManagerService {

	@Autowired
	private EmergencyPreMapper emergencyPreMapper;
	
	@Autowired
	private YuAnActivitiMapper yuAnActivitiMapper;
	
	@Value("${project.imgupload.rootPath}")
	private String uploadPath;
	
	 @Value("${project.imgreq.rootPath}")
	  private String rootPath;

	 @Value("${server.path}")
	private String path;
	 
	 @Value("${server.port}")
	 private String port;
	
	@Override
	public void addEmergencyInf(EmergencyPreReqInfo preInfo) 
	{
		String docUrl =preInfo.getDoc_url();
		int i =docUrl.lastIndexOf("=");
		String localUrl=docUrl.substring(i+1,docUrl.length()-1);
		String fileName=preInfo.getDoc_url().substring(1, i);
		String newUrl ="http://"+ path+":"+port + rootPath +"file/"+localUrl;
		String locFile =uploadPath+"file/"+localUrl;
		log.info("获取文件大小文件路径:{}",locFile);
	    if(StringUtils.isNotBlank(locFile))
	    {
	     // 获取文件大小
	        int buff;
	        
	        FileInputStream  input = null;
	        String size = null;
	        try
	        {
	            
	            input = new FileInputStream(locFile);
	            buff = input.available();
	            input.close();
	            if (buff < 1000000)
	            {
	                size = buff/1024 + "kb";
	            }
	            else
	            {
	                buff = buff/1024 ; 
	                size = buff/1024 + "M";
	            }
	        } 
	        catch (FileNotFoundException e)
	        {
	            log.error("文件找不到");
	        } 
	        catch (IOException e)
	        {
	        	log.error("流异常");
	        }
	       log.info("添加文件大小为:{}" , size);
	        preInfo.setSizes(size);
	        preInfo.setDoc_name(fileName);
	        preInfo.setDoc_url(newUrl);
	    }
		 emergencyPreMapper.addEmergencyInf(preInfo);
	}
	
	
	@Override
	public void updateEmergencyInf(EmergencyPreReqInfo preInfo) {
		emergencyPreMapper.updateEmergencyInf(preInfo);
	}

	@Override
	public void delEmergencyInf(String id) {
		emergencyPreMapper.delEmergencyInf(id);	
	}

	@Override
	public List<EmergencyPreRespInfo> emergencyPreList(int pageNumber, int pageSize, String pre_name, String pre_type) {
		PageHelper.startPage(pageNumber, pageSize);
		Map<String, String> map = new HashMap<String, String>();
		map.put("pre_name", pre_name);
		map.put("pre_type", pre_type);
		return emergencyPreMapper.emergencyPreList(map);
	}

	@Override
	public List<EmergencyPreDetailsRespInfo> emergencyPreDetails(String id) {
		
		List<EmergencyPreDetailsRespInfo> list =emergencyPreMapper.emergencyPreDetails(id);
		for(EmergencyPreDetailsRespInfo info : list) {
			List<PositionRespInfo> positionInfo=emergencyPreMapper.getPosition(info.getId());
			info.setPositionInfo(positionInfo);
		}
		return list;
		
	}

	@Override
	public void addPositionInf(PositionReqInfo preInfo) {
		Map<String, String> map = new HashMap<>();
		map.put("pre_id", preInfo.getPre_id());
		map.put("position_id",preInfo.getPosition_id() );
//		map.put("user_id",preInfo.getUser_id() );
		if(preInfo.getContentInfo()!=null) {
			for(PositionContentInfo info :preInfo.getContentInfo()) {
				map.put("num", info.getNum());
				map.put("content", info.getContent());
				emergencyPreMapper.addPositionInf(map);
			}
		}
		
	}

	@Override
	public void addTroubleInf(TroubleReqInfo troubleInfo) {
		emergencyPreMapper.addTroubleInf(troubleInfo);
	}

	@Override
	public void updateTroubleInf(TroubleReqInfo preInfo) {
		emergencyPreMapper.updateTroubleInf(preInfo);	
	}

	@Override
	public void delTroubleInf(String id) {
		emergencyPreMapper.delTroubleInf(id);	
	}

	@Override
	public List<TroubleRespInfo> troubleList(int pageNumber, int pageSize, String department_id, String start_time,
			String end_time,String category) {
		PageHelper.startPage(pageNumber, pageSize);
		Map<String, String> map = new HashMap<String, String>();
		map.put("department_id", department_id);
		map.put("start_time", start_time);
		map.put("end_time", end_time);
		map.put("category", category);
		return emergencyPreMapper.troubleList(map);
	}

	/**
	 * 查询预案详情
	 */
	@Override
	public List<EmergencyPreDetailsRespInfo> preDetails(String id) {
		List<EmergencyPreDetailsRespInfo> list =emergencyPreMapper.preDetails(id);
		for(EmergencyPreDetailsRespInfo info : list) 
		{
		    
            OrganizationName organizations = emergencyPreMapper.getUserOrganization(info.getDepartment_id());
            String o_name = "";
            if(StringUtils.isNotBlank(organizations.getName1()))
            {
                o_name = o_name + organizations.getName1()+"-";
            }
            if(StringUtils.isNotBlank(organizations.getName2()))
            {
                o_name =o_name + organizations.getName2()+"-";
            }
            if(StringUtils.isNotBlank(organizations.getName3()))
            {
                o_name = o_name + organizations.getName3()+"-";
            }
            if(StringUtils.isNotBlank(o_name))
            {
                o_name = o_name.substring(0,o_name.length() - 1);
            }
            info.setDepartment_name(o_name);
		    
		    
			List<PositionRespInfo> positionInfo=emergencyPreMapper.getPosition(info.getId());
			for(PositionRespInfo position : positionInfo)
			{
			    String role = emergencyPreMapper.getUserRoleAndOrganization(position.getPosition_id());
			    position.setRoleName(role);
			    OrganizationName organization = emergencyPreMapper.getUserOrganization(position.getPosition_id());
			    String name = "";
			    if(StringUtils.isNotBlank(organization.getName1()))
			    {
			        name = name + organization.getName1()+"-";
			    }
			    if(StringUtils.isNotBlank(organization.getName2()))
                {
                    name = name + organization.getName2()+"-";
                }
			    if(StringUtils.isNotBlank(organization.getName3()))
                {
                    name = name + organization.getName3()+"-";
                }
			    if(StringUtils.isNotBlank(name))
			    {
		             name = name.substring(0,name.length() - 1);
			    }
                position.setOrganization(name);
			}
			info.setPositionInfo(positionInfo);
			List<EmergencyWarnReqInfo> warnInfo = emergencyPreMapper.getWarnList(info.getId());
			info.setWarnInfo(warnInfo);
			List<EmergencyWarnStartUpReqInfo> warnstart = emergencyPreMapper.getWarnStartUpList(info.getId());
			info.setWarnstartUpInfo(warnstart);
		}
		return list;
	}

	@Override
	public void delPositionInf(String id) {
		emergencyPreMapper.delPositionInf(id);
	}

	@Override
	public void updatePositionInf(PositionReqInfo preInfo) {
	    for(PositionContentInfo info : preInfo.getContentInfo())
	    {
	        emergencyPreMapper.updatePositionInf(info);
	    }
	}

	@Override
	public List<AppDutyContentInfo> dutyDetailsByApp(String pre_id,String position_id) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("pre_id", pre_id);
		map.put("position_id", position_id);
		return emergencyPreMapper.dutyDetailsByApp(map);
	}


	@Override
	public void addEvacuationInf(EmergencyEvacuationReqInfo evaInfo) {
		emergencyPreMapper.addEvacuationInf(evaInfo);
	}


	@Override
	public void updateEvacuationInf(EmergencyEvacuationReqInfo evaInfo) {
		emergencyPreMapper.updateEvacuationInf(evaInfo);
	}


	@Override
	public void delEvacuationInf(String id) {
		emergencyPreMapper.delEvacuationInf(id);
	}


	@Override
	public List<EmergencyEvacuationReqInfo> evacuationList(int pageNumber, int pageSize, String location,
			String object) {
		PageHelper.startPage(pageNumber, pageSize);
		Map<String, String> map = new HashMap<String, String>();
		map.put("location", location);
		map.put("object", object);
		return emergencyPreMapper.evacuationList(map);
	}


	@Override
	public WorkFlowInfo getWorkFlow() {
		WorkFlowInfo workFlowInfo =new WorkFlowInfo();
		workFlowInfo.setYuanWorkFlowInfo(emergencyPreMapper.getYuanWorkFlow());
		workFlowInfo.setJiHuaWorkFlowInfo(emergencyPreMapper.getJiHuaWorkFlow());
		workFlowInfo.setWuZhiWorkFlowInfo(emergencyPreMapper.getWuZhiWorkFlow());
		return workFlowInfo ;
	}


	@Override
	public void startEmergencyState(String id) {
		emergencyPreMapper.startEmergencyState(id);	
	}


	@Override
	public List<SignTaskListInfo> getPositionWithTask(String pre_id, String position) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("pre_id", pre_id);
		map.put("position", position);
		return emergencyPreMapper.getPositionWithTask(map);
	}


	@Override
	public void endEergencyState(String pre_id) {
		emergencyPreMapper.endEergencyState(pre_id);		
	}


	@Override
	public void updateSignStat(String pre_id, String position_id) {
		Map<String, String> map = new HashMap<String, String>();
		map.put("pre_id", pre_id);
		map.put("position_id", position_id);
		 emergencyPreMapper.updateSignStat(map);		
	}


	@Override
	public boolean selectAllSignState(String pre_id) {
		List<AllSignStateInfo> signInfo=emergencyPreMapper.selectAllSignState(pre_id);
		for(AllSignStateInfo infos :signInfo) {
			if(!"2".equals(infos.getState())) {
				return false;
			}
		}
		return true;
	}


	@Override
	public YuanProcessInfo getYuanProcessInfo(String pre_id) {
		YuanProcessInfo processInfo=emergencyPreMapper.getYuanProcessInfo(pre_id);
		
		List<SingUserInfo> positionInfo=emergencyPreMapper.getYuanSingUserInfo(pre_id);
		processInfo.setPositionInfo(positionInfo);
		return processInfo;
	}


	@Override
	public YuAnProcessReqInfo editorYuanProcessInfo(YuAnProcessReqInfo preInfo) {
		return emergencyPreMapper.editorYuanProcessInfo(preInfo);
	}

	/**
	 * 应急预案管理-添加预案标准(参数)接口
	 */
    @Override
    public void addWarnInfo(EmergencyWarnReqInfo warnInfo) 
    {
        warnInfo.setId(getCard());
        emergencyPreMapper.addWarnInfo(warnInfo);      
    }

    /**
     * 应急预案管理-添加预案启动标准(参数)接口
     */
    @Override
    public void addWarnStartUpInfo(EmergencyWarnStartUpReqInfo startInfo) 
    {
        startInfo.setId(getCard());
        emergencyPreMapper.addWarnStartUpInfo(startInfo);      
    }


  //生成随机数
    public static String getCard()
    {
        Random rand=new Random();//生成随机数
        String cardNnumer="";
        for(int a=0;a<9;a++)
        {
            cardNnumer+=rand.nextInt(10);//生成6位数字
        }
        log.info("增加组织结构部门信息 生成ID:{}",cardNnumer);

        return cardNnumer;
    }


	@Override
	public List<YuAnActivitiDetailsRespInfo> getWorkFlowDetails(String pre_id) {
		List<YuAnActivitiDetailsRespInfo> list =yuAnActivitiMapper.yuAnDetails(pre_id);
		for(YuAnActivitiDetailsRespInfo info : list) 
		{
			List<YuAnActivitiPositionRespInfo> positionInfo=yuAnActivitiMapper.getPosition(info.getId());
			info.setPositionInfo(positionInfo);
			List<YuAnactivitiWarnRespInfo> warnInfo = yuAnActivitiMapper.getWarnList(info.getId());
			info.setWarnInfo(warnInfo);
			List<YuanWarnStartUpRespInfo> warnstart = yuAnActivitiMapper.getWarnStartUpList(info.getId());
			info.setWarnstartUpInfo(warnstart);
		}
		return list;
	}


	@Override
	public YuAnWorkFlowStartInfo getDepartMentId(String id) {
		return yuAnActivitiMapper.getDepartMentId(id);
	}


	@Override
	public YuAnProcessReqInfo getStepTwoInfo() {
		// TODO Auto-generated method stub
		return yuAnActivitiMapper.getStepTwoInfo();
	}

	/**
	 * 插入预案启动选择的预案启动参数 
	 */
    @Override
    public void insertStartWorkFlowParm(YuAnWorkFlowStartParm info) 
    {
        yuAnActivitiMapper.insertWarnStartParm(info);
        for(String warnid : info.getWarnids())
        {
            Map<String, String> pa = new HashMap<String, String>();
            pa.put("p_id", info.getId());
            pa.put("warnid", warnid);
            yuAnActivitiMapper.insertWarnParm(pa);
        }
    }

    /**
     * 应急预案管理-删除预案标准(参数)接口
     * @param id
     */
    @Override
    public void delwarnInf(String w_id) 
    {
        emergencyPreMapper.delwarnInf(w_id);
    }

    /**
     * 应急预案管理-删除预案启动标准(参数)接口
     * @param id
     */
    @Override
    public void delwarnstartupInf(String w_id) 
    {
        emergencyPreMapper.delwarnstartupInf(w_id);
    }

    /**
     * 应急预案管理-修改预案标准(参数)接口
     * @param info
     */
    @Override
    public void updateWarnInf(EmergencyWarnReqInfo info) 
    {
        emergencyPreMapper.updateWarnInf(info);;
    }

    /**
     * 应急预案管理-修改预案启动标准(参数)接口
     * @param info
     */
    @Override
    public void updateWarnstartupInf(EmergencyWarnStartUpReqInfo info) 
    {
        emergencyPreMapper.updateWarnstartupInf(info);
    }
}
